import re
from utils.logger import get_logger

logger = get_logger(__name__)

class QueryEngine:
    def __init__(self, connection_manager):
        self.connection_manager = connection_manager

    def execute_query(self, query):
        if not self.connection_manager.current_connection:
            return [], "未选择数据库连接"

        # 先去除 /* ... */ 多行注释
        clean_query = re.sub(r'/\*.*?\*/', '', query, flags=re.DOTALL)
        # 再去除 -- 注释（包括行内和行尾）
        clean_query = re.sub(r'--.*?$', '', clean_query, flags=re.MULTILINE)
        # 去除每行首尾空白，并过滤空行
        clean_query = '\n'.join(
            line.strip() for line in clean_query.splitlines() if line.strip()
        )

        if not clean_query:
            return [], "空查询"

        try:
            rows, msg = self.connection_manager.execute_query(clean_query)
            return rows, msg
        except Exception as e:
            logger.error(f"执行查询时出错: {e}")
            return [], f"执行错误: {e}"